# -*- coding: utf-8 -*-

from openerp.addons.web import http
from openerp.addons.web.http import request

import os
import sys
import jinja2
import simplejson
from openerp import SUPERUSER_ID
from openerp.osv import osv

from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug
from jinjia2_cache import FragmentCacheExtension

from werkzeug.contrib.cache import SimpleCache


##############################################
# 模板配置
##############################################
if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
    staic_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'static'))
    static_loader = jinja2.FileSystemLoader(staic_path)
else:
    loader = jinja2.PackageLoader('openerp.addons.website_mshop', "html")
    static_loader = jinja2.PackageLoader('openerp.addons.website_mshop', "static")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True, extensions=[FragmentCacheExtension])
static_env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=static_loader, autoescape=True, extensions=[FragmentCacheExtension])


##############################################
# 商城请求
##############################################
class WebsiteShop(http.Controller):
    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps
        env.fragment_cache = SimpleCache()

    def _parse_int(self, parsed_value):
        try:
            parse_value = int(parsed_value)
        except ValueError:
            # TODO 应该需要返回一个错误的response
            raise osv.except_osv(u'错误', u'遇到一个无法解析的id')

        return parse_value

    def _parse_float(self, parsed_value):
        try:
            parse_value = float(parsed_value)
        except ValueError:
            # TODO 应该需要返回一个错误的response
            raise osv.except_osv(u'错误', u'遇到一个无法解析的id')

        return parse_value

    def _set_get_cart(self, get_cart=True):
        request.session['get_cart'] = get_cart

    def _match_attribute(self, product, attribute):
        return all(value.id in attribute for value in product.attribute_value_ids)

    def _prepare_attribute_product(self, product):
        return {
            'id': product.id,
            'price_unit': product.lst_price,
            'qty_available': product.qty_available,
            'uom': product.uom_id.name,
            'variant': True,
            'is_group': (product.start_sale_time or product.end_sale_time) and True or False,
            'start_time': product.start_sale_time or '',
            'end_time': product.end_sale_time or '',
            'minimum_quantity': product.minimum_quantity,
            'reserve_quantity': product.reserve_quantity,
            # 'name': product.name,
            # 'description_sale': product.description_sale,
        }

    def _check_login(self):
        if request.session.get('login'):
            return True

        return False

    def _prepare_multi_address(self, address):
        return {
            'id': address.id,
            'unlink': False,
            'province': address.contacts_id.province_id.name,
            'city': address.contacts_id.city_id.city_name,
            'country': address.contacts_id.county_id.county_name,
            'street': address.contacts_id.street,
            'zip': address.contacts_id.zip,
            'name': address.contacts_id.name,
            'phone': address.contacts_id.phone,
        }

    def _prepare_order_line(self, line):
        return {
            'id': line.id,
            'product_id': line.product_id.id,
            'product_name': line.product_id.name,
            'name': line.name,
            'attribute': ','.join(value.attribute_id.name + ':' + value.name for value in line.product_id.attribute_value_ids),
            # 'attribute': {value.attribute_id.name: value.name for value in line.product_id.attribute_value_ids},
            'price_unit': line.price_unit,
            'product_qty': line.product_uom_qty,
        }

    def _get_default_counts(self, partner_id):
        cr = request.cr
        sql_text = 'SELECT COUNT(*) FROM sale_order WHERE partner_id = %s AND state IN %s'

        map_order_state = [
            ('confirm_count', "('draft')"),
            ('stock_count', "('progress', 'manual')"),
            ('evaluation_count', "('done')"),
        ]

        res = {}
        for state in map_order_state:
            cr.execute(sql_text % (str(partner_id), state[1]))

            try:
                count = cr.fetchall()[0][0]
            except IndexError:
                count = 0

            res[state[0]] = count

        return res

    def _get_default_address(self, order, partner):
        contacts = order and order.contacts_id or partner.main_contacts
        if contacts:
            return self._prepare_multi_address(contacts)

        return {}

    def _get_address_by_order(self, order):
        if order.consignee:
            return {
                'province': order.province_id.name or '',
                'city': order.city_id.city_name or '',
                'country': order.county_id.county_name or '',
                'street': order.street or '',
                'zip': order.zip or '',
                'name': order.consignee or '',
                'phone': order.mobile_number or '',
            }
        else:
            return self._get_default_address(order, order.partner_id)

    def _get_sale_order(self, order):
        res = []
        for line in order.order_line:
            res.append(self._prepare_order_line(line))

        return res

    def _get_note(self, order):
        return order.note or ''

    def _get_state(self, order):
        return order.state

    def _get_product_info(self, pool, cr, uid, ids, context=None):
        res = []
        for product in pool.browse(cr, uid, ids, context=context):
            res.append({
                    'id': product.id,
                    'name': product.name,
                    'description_sale': product.description_sale,
                    'price': product.lst_price,
                    'popularity': 16,
                })

        return res

    def _get_children_category(self, category):
        res = []
        for child in category.child_id:
            child_res = {'name': child.name, 'childrens': []}
            for third_child in child.child_id:
                child_res['childrens'].append({'name': third_child.name, 'id': third_child.id})

            res.append(child_res)

        return res

    @http.route(['/mshop', '/mshop/<string:page>'], auth='weixin', website=True)
    def shop_html(self, page='home', **kw):
        # kw.update({"page": page})
        template = static_env.get_template('/mshop_vue/dist/index.html')
        return template.render({})
        # template = env.get_template(page + ".html")
        # return template.render(kw)

    @http.route('/mshop/search', auth='public', website=True)
    def search(self, word=None, **kw):
        kw.update({'word': word or ''})
        template = env.get_template('search.html')

        return template.render(kw)

    @http.route('/mshop/search/get_list', auth='public', website=True)
    def search_get_list(self, word=None, **kw):
        cr, context, pool = request.cr, request.context, request.registry

        domain = word and ['|', ('default_code', 'ilike', word), ('name', 'ilike', word)] or []

        product_obj = pool.get('product.template')
        res_ids = product_obj.search(cr, SUPERUSER_ID, domain, context=context)

        return request.make_response(simplejson.dumps(
                self._get_product_info(product_obj, cr, SUPERUSER_ID, res_ids, context=context)
            ))

    @http.route('/mshop/products/get', auth='public', website=True)
    def products_get(self, last_index, numbers, categ_id=None, brand_id=None, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        domain = [('company_id', '=', 1), ('sale_ok', '=', True), ('type', '!=', 'service'), ('is_end_time', '!=', True)]

        if categ_id != 'false':
            domain.append(('public_categ_ids', 'in', self._parse_int(categ_id)))

        if brand_id != 'false':
            domain.append(('product_brand_id', '=', self._parse_int(brand_id)))

        return request.make_response(simplejson.dumps(
                pool.get('product.template').search_read(cr, SUPERUSER_ID, domain,
                    ['name', 'description_sale', 'lst_price'], limit=self._parse_int(numbers),
                    offset=self._parse_int(last_index), context=context)
            ))

    @http.route('/mshop/product', auth='public', website=True)
    def product(self, product_id, **kw):
        kw.update({"id": self._parse_int(product_id)})
        template = env.get_template("product.html")
        return template.render(kw)

    @http.route('/mshop/product/get_attribute', auth='public', website=True)
    def get_attribute(self, product_id, **kw):
        cr, context, pool = request.cr, request.context, request.registry

        product_id = self._parse_int(product_id)
        product = pool.get('product.template').browse(cr, SUPERUSER_ID, product_id, context=context)

        response_dict, response_list = {}, []
        for product in product.product_variant_ids:
            if product.is_end():
                continue

            for value in product.attribute_value_ids:
                if response_dict.get(value.attribute_id.id):
                    attribute_value = response_dict[value.attribute_id.id]['value']
                    if not attribute_value.get(value.id):
                        attribute_value[value.id] = {'name': value.name, 'disable': False, 'product': []}
                else:
                    response_dict[value.attribute_id.id] = {
                        'name': value.attribute_id.name,
                        'value': {value.id: {'name': value.name, 'disable': False, 'product': []}},
                        # 'value_id': value.id,
                        'choose': False,
                    }

                # 在这里可以添加一下在界面上显示但是不让选择的产品属性
                response_dict[value.attribute_id.id]['value'][value.id]['product'].append(product.id)

        for key, response in response_dict.iteritems():
            value_list = []
            for value_key, value in response['value'].iteritems():
                value.update({'value_id': value_key, 'product': list(set(value['product']))})
                value_list.append(value)

            response.update({
                'attribute_id': key,
                'choose': len(value_list) == 1 and value_list[0] or False,
                'value': value_list,
            })

            response_list.append(response)

        return request.make_response(simplejson.dumps(response_list))

    @http.route('/mshop/product/get_product_by_attribute', auth='public', website=True)
    def get_product_by_attribute(self, attribute):
        cr, context, pool = request.cr, request.context, request.registry
        attribute = simplejson.loads(attribute)

        tmpl_id = self._parse_int(attribute.pop('tmpl_id'))
        template = pool.get('product.template').browse(cr, SUPERUSER_ID, tmpl_id, context=context)

        product_vals = {}
        for product in template.product_variant_ids:
            if self._match_attribute(product, attribute.get('attributes', [])):
                product_vals = self._prepare_attribute_product(product)
                break

        return request.make_response(simplejson.dumps(product_vals))

    @http.route('/mshop/shopping_cart', auth='public', website=True)
    def cart(self, **kw):
        self._set_get_cart(True)
        cart = request.website.sale_get_order()

        kw.update({'cart_id': cart.id})
        template = env.get_template("shopping_cart.html")
        return template.render(kw)

    @http.route('/mshop/shopping_cart/get', auth='public', website=True)
    def cart_get(self, **kw):
        self._set_get_cart(True)
        cart = request.website.sale_get_order()
        return request.make_response(simplejson.dumps(
                cart.get_cart_line_info(context=request.context)
            ))

    @http.route('/mshop/shopping_cart/add', auth='public', website=True)
    def cart_add(self, product_id, add_qty=1, **kw):
        product_id = self._parse_int(product_id)

        if product_id:
            self._set_get_cart(True)
            cart = request.website.sale_get_order()
            cart._cart_update(product_id=product_id, add_qty=self._parse_int(add_qty))

        return request.redirect('/mshop/shopping_cart')

    @http.route('/mshop/shopping_cart/buy_now', auth='public', website=True)
    def cart_buy_now(self, product_id, add_qty=1, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        product_id = self._parse_int(product_id)

        if product_id:
            self._set_get_cart(False)

            request.session['sale_order_id'] = False
            request.session['cart_id'] = False
            product = pool.get('product.product').browse(cr, SUPERUSER_ID, product_id, context=context)
            prepare_vals = [{
                'product_id': product.id,
                'product_uom_qty': add_qty,
                'price_unit': product.lst_price,
                'name': product.description_sale and "%s\n%s" % (product.display_name,
                    product.description_sale) or product.display_name or product.name,
            }]

            order = request.website.sale_get_order(force_create=True, prepare_vals=prepare_vals)
            return request.make_response(str(order.id))

    @http.route('/mshop/shopping_cart/update_cart', auth='public', website=True)
    def cart_update(self, line_id=None, qty=0, cart_line=None, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        line_obj = pool.get('shopping.cart.line')

        if cart_line:
            unlink_ids = []
            for line_id, value in simplejson.loads(cart_line).iteritems():
                line_id = self._parse_int(line_id)
                if value.get('state') == 'delete':
                    unlink_ids.append(line_id)
                    continue

                res = {
                    'state': value.get('state', 'draft'),
                    'product_uom_qty': self._parse_float(value.get('product_uom_qty', 0))
                }

                line_obj.write(cr, SUPERUSER_ID, line_id, res, context=context)

            if unlink_ids:
                line_obj.write(cr, SUPERUSER_ID, unlink_ids, {'state': 'delete'}, context=context)

            return request.make_response('')

        line_id = self._parse_int(line_id)
        qty = self._parse_float(qty)

        if line_id and qty > 0:
            line_obj.write(cr, SUPERUSER_ID, line_id, {'product_uom_qty': qty}, context=context)
        elif line_id and qty <= 0:
            line_obj.write(cr, SUPERUSER_ID, line_id, {'state': 'delete'}, context=context)

        return request.make_response('')

    @http.route('/mshop/shopping_cart/clearing', auth='public', website=True)
    def cart_clearing(self, line=None, *kw):
        cr, context, pool = request.cr, request.context, request.registry

        if line:
            line_ids = map(int, simplejson.loads(line))
            cart = request.website.sale_get_order()

            sale_id = pool.get('shopping.cart').create_partial_sale_order(cr, SUPERUSER_ID, cart, line_ids, context=context)
            request.session['sale_order_id'] = sale_id

        return request.make_response(str(sale_id))
        # 需要直接重定位到订单确认页面
        # return request.redirect('/mshop/order')

    @http.route('/mshop/customer/address/get_multi', auth='public', website=True)
    def multi_address(self, partner_id=None, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        partner = pool.get('res.partner').browse(cr, SUPERUSER_ID, self._parse_int(partner_id), context=context)
        address_vals = []

        for address in (address for address in partner.child_contacts_ids if address.is_inauguratory):
            address_vals.append(self._prepare_multi_address(address))

        return request.make_response(simplejson.dumps(address_vals))

    @http.route('/mshop/customer/address', auth='public', website=True)
    def address(self, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        if not self._check_login():
            return request.redirect('mshop/login')

        user = pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
        kw.update({'partner_id': user.partner_id.id})

        template = env.get_template("address.html")
        return template.render(kw)

    @http.route('/mshop/customer/address/update_default', auth='public', website=True)
    def address_update_default(self, address_id=None, **kw):
        cr, context, pool = request.cr, request.context, request.registry

        address_obj = pool.get('company.customer')
        if address_id:
            address_id = self._parse_int(address_id)
            address_obj.write(cr, SUPERUSER_ID, address_id, {'is_main_contacts': True}, context=context)

        return request.make_response('')

    @http.route('/mshop/customer/address/unlink', auth='public', website=True)
    def address_unlink(self, address_id, **kw):
        cr, context, pool = request.cr, request.context, request.registry

        if address_id:
            address_id = self._parse_int(address_id)
            pool.get('company.contacts').write(cr, SUPERUSER_ID, [address_id], {'is_inauguratory': False}, context=context)

        return request.make_response('')

    @http.route('/mshop/customer/address/edit', auth='public', website=True)
    def address_edit(self, **kw):
        template = env.get_template('address_edit.html')
        return template.render(kw)

    @http.route('/mshop/customer/address/get', auth='public', website=True)
    def address_get(self, address_id=None, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        address_id = self._parse_int(address_id)

        if address_id:
            address = self._prepare_multi_address(pool.get('company.contacts').browse(cr, SUPERUSER_ID, address_id, context=context))
            address.update({'state': 'edit', 'title': u'编辑地址'})
            address.update({'province': ' '.join([address.pop('province') or '', address.pop('city') or '', address.pop('country') or ''])})

        else:
            address = {'state': 'new', 'title': u'新建地址'}

        return request.make_response(simplejson.dumps(address))

    @http.route('/mshop/customer/address/update', auth='public', website=True)
    def address_update(self, partner_id, value=None, **kw):
        if partner_id and value:
            cr, context, pool = request.cr, request.context, request.registry
            partner_id = self._parse_int(partner_id)
            value = simplejson.loads(value)

            state_obj = pool.get('res.country.state')
            city_obj = pool.get('all.city')
            country_obj = pool.get('all.county')

            address = value.pop('province').split()
            if len(address) == 2:
                province, city, country = address[0], address[0], address[1]
            else:
                province, city, country = address[0], address[1], address[2]

            state_ids = state_obj.search(cr, SUPERUSER_ID, [('name', 'ilike', province)], context=context)
            city_ids = city_obj.search(cr, SUPERUSER_ID, [('city_name', 'ilike', city)], context=context)
            country_ids = country_obj.search(cr, SUPERUSER_ID, [('county_name', 'ilike', country)], context=context)

            if state_ids:
                state_id = state_ids[0]
            else:
                raise osv.except_osv(u'错误', u'odoo后台数据不存在该省份%s' % province)

            if city_ids:
                city_id = city_ids[0]
            else:
                city_id = city_obj.create(cr, SUPERUSER_ID, {'city_name': city, 'province_id': state_id}, context=context)

            if country_ids:
                country_id = country_ids[0]
            else:
                country_id = country_obj.create(cr, SUPERUSER_ID, {'county_name': country, 'city_id': city_id}, context=context)

            value.update({
                    'province_id': state_id,
                    'city_id': city_id,
                    'county_id': country_id,
                    # 'partner_id': partner_id,
                })

            if value.get('id'):
                contacts = pool.get('company.contacts').browse(cr, SUPERUSER_ID, value.get('id'), context=context)
                contacts.contacts_id.write(value)
            # else:
                # pool.get('res.partner').create(cr, SUPERUSER_ID, value, context=context)

        # return request.redirect('/mshop/customer/address')

    @http.route('/mshop/customer/address/choose', auth='public', website=True)
    def address_choose(self, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        if not self._check_login():
            return request.redirect('mshop/login')

        user = pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
        kw.update({'partner_id': user.partner_id.id})

        template = env.get_template("address_choose.html")
        return template.render(kw)

    @http.route('/mshop/customer/address/choosed', auth='public', website=True)
    def address_choosed(self, choose_id=None, order_id=None, **kw):
        cr, context, pool = request.cr, request.context, request.registry

        if choose_id and order_id:
            choose_id, order_id = self._parse_int(choose_id), self._parse_int(order_id)
            order = pool.get('sale.order').browse(cr, SUPERUSER_ID, order_id, context=context)
            if order.state == 'draft':
                contacts = order.onchange_contacts(choose_id, context=context)
                contacts = contacts.get('value', {})
                contacts.update({'contacts_id': choose_id})
                order.write(contacts, context=context)

    @http.route('/mshop/order', auth='public', website=True)
    def order(self, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        if not self._check_login():
            return request.redirect('mshop/login')

        if kw.get('order_id'):
            kw.update({'order_id': self._parse_int(kw.get('order_id'))})
            template = env.get_template('order.html')
        else:
            template = env.get_template('order_list.html')

            user = pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
            kw.update({'partner_id': user.partner_id.id})

            request.session['state'] = kw.get('state') or ''

        return template.render(kw)

    @http.route('/mshop/order/post_message', auth='public', website=True)
    def order_post_message(self, order_id, message, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        res_id = pool.get('sale.order').message_post(cr, uid, [self._parse_int(order_id)],
            body=message, type='email', context=context)

        message = pool.get('mail.message').browse(cr, SUPERUSER_ID, res_id, context=context)
        return request.make_response(simplejson.dumps(pool.get('sale.order').prepare_message(message)))

    @http.route('/mshop/order/get', auth='public', website=True)
    def order_get(self, args=None, order_id=None, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        if args and order_id:
            args, order_id = simplejson.loads(args), self._parse_int(order_id)
            order = pool.get('sale.order').browse(cr, SUPERUSER_ID, order_id, context=context)
            user = pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)

            res = {'partner_id': user.partner_id.id, 'invoice': order.invoiced and u'已付款' or u'未付款'}
            if 'address' in args:
                res.update({'address': self._get_address_by_order(order)})
            if 'order_line' in args:
                res.update({'order_line': self._get_sale_order(order)})
            if 'note' in args:
                res.update({'note': self._get_note(order)})
            if 'state' in args:
                res.update({'state': self._get_state(order)})

            return request.make_response(simplejson.dumps(res))

    @http.route('/mshop/order/confirm', auth='public', website=True)
    def order_confirm(self, order_id, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        if order_id:
            pool.get('sale.order').action_button_confirm(cr, SUPERUSER_ID, [self._parse_int(order_id)], context=context)

    @http.route('/mshop/order/get_list', auth='public', website=True)
    def order_get_list(self, partner_id, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        if partner_id:
            partner_id = self._parse_int(partner_id)
        else:
            user = pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
            partner_id = user.partner_id.id

        domain = [('partner_id', '=', partner_id)]
        if request.session.get('state'):
            domain.append(('state', 'in', request.session.get('state').split(',')))

        order_ids = pool.get('sale.order').search(cr, SUPERUSER_ID, domain, context=context)
        res = []
        for order in pool.get('sale.order').browse(cr, SUPERUSER_ID, order_ids, context=context):
            res.append({
                    'id': order.id,
                    'name': order.name,
                    'amount_total': order.amount_total,
                    'order_line': [line.product_id.id for line in order.order_line],
                    'invoice': order.invoiced and u'已付款' or u'未付款',
                })

        return request.make_response(simplejson.dumps(res))

    @http.route('/mshop/my', auth='public', website=True)
    def my(self, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        user = pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)

        kw.update({'partner_id': user.partner_id.id})
        template = env.get_template("my.html")

        return template.render(kw)

    @http.route('/mshop/my/get', auth='public', website=True)
    def my_get(self, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        user = pool.get('res.users').browse(cr, SUPERUSER_ID, request.uid, context=context)

        res = {
            'name': user.partner_id.name,
            'address': self._get_default_address(False, user.partner_id),
            'counts': self._get_default_counts(user.partner_id.id),
            'partner_id': user.partner_id.id,
        }

        return request.make_response(simplejson.dumps(res))

    @http.route('/mshop/my/info', auth='public', website=True)
    def my_info(self, **kw):
        template = env.get_template("my_edit.html")
        return template.render(kw)

    @http.route('/mshop/my/info/get', auth='public', website=True)
    def my_info_get(self, partner_id, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        partner = pool.get('res.partner').browse(cr, SUPERUSER_ID, self._parse_int(partner_id), context=context)

        res = {
            'name': partner.name,
            'phone': partner.phone,
            'mobile': partner.mobile,
            'email': partner.email,
        }

        return request.make_response(simplejson.dumps(res))

    @http.route('/mshop/my/info/update', auth='public', website=True)
    def my_info_update(self, partner_id, value=None, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        if value:
            partner_id, value = self._parse_int(partner_id), simplejson.loads(value)
            pool.get('res.partner').write(cr, SUPERUSER_ID, partner_id, value, context=context)

    @http.route('/mshop/order/evaluation', auth='public', website=True)
    def evaluation(self, line_id, evaluation_id=None, **kw):
        template = env.get_template('evaluation.html')

        if line_id:
            kw.update({'line_id': self._parse_int(line_id)})

        kw.update({'evaluation_id': evaluation_id and self._parse_int(evaluation_id) or 'false'})
        return template.render(kw)

    @http.route('/mshop/order/evaluation/submit', auth='public', website=True)
    def evaluation_submit(self, line_id, description, is_anonymous, stars, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        evaluation_obj = pool.get('order.evaluation')
        evaluation_obj.create(cr, SUPERUSER_ID, {
                'line_id': self._parse_int(line_id),
                'description': description,
                'is_anonymous': is_anonymous != 'false',
                'user_type': 'buyer',
                'star_ids': [(0, 0, {'star_config_id': self._parse_int(star.get('id')), 'level': str(star.get('level'))}) for star in simplejson.loads(stars)],
                'user_id': self._check_login and pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id or False,
            }, context=context)

    @http.route('/mshop/product/evaluations', auth='public', website=True)
    def evaluations_get(self, template_id, **kw):
        template = env.get_template('evaluations.html')
        if template_id:
            kw.update({'template_id': self._parse_int(template_id)})

        return template.render(kw)

    @http.route('/mshop/order/evaluation/get_description', auth='public', website=True)
    def evaluation_description_get(self, evaluation_id, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        evaluation = pool.get('order.evaluation').browse(cr, SUPERUSER_ID, self._parse_int(evaluation_id), context=context)

        return request.make_response(simplejson.dumps({'description': evaluation.description, 'is_anonymous': evaluation.is_anonymous, 'need_image': evaluation.order_id and True or False}))

    @http.route('/mshop/category', auth='public', website=True)
    def category(self, **kw):
        template = env.get_template('category.html')

        return template.render(kw)

    @http.route('/mshop/category/specific', auth='public', website=True)
    def specific_category(self, categ_id, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        category = pool.get('product.public.category').browse(cr, SUPERUSER_ID, self._parse_int(categ_id), context=context)

        return request.make_response(simplejson.dumps(
                self._get_children_category(category)
            ))

    @http.route('/mshop/brand', auth='public', website=True)
    def brand(self, **kw):
        template = env.get_template('brand.html')

        return template.render(kw)

    @http.route('/mshop/order/message', auth='public', website=True)
    def message(self, order_id=None, **kw):
        template = env.get_template('message.html')
        if order_id:
            kw.update({'order_id': self._parse_int(order_id)})

        return template.render(kw)

    @http.route('/mshop/document', auth='public', website=True)
    def document(self, wall_id, **kw):
        template = env.get_template('document.html')
        kw.update({'wall_id': self._parse_int(wall_id)})

        return template.render(kw)

    @http.route('/mshop/get_enterprise_info', auth='public', website=True)
    def get_enterprise_info(self, **kw):
        cr, context, pool = request.cr, request.context, request.registry
        application_obj = pool.get('wechat.application')

        application_ids = application_obj.search(cr, SUPERUSER_ID, [], context=context)
        if application_ids:
            application = application_obj.browse(cr, SUPERUSER_ID, application_ids[0], context=context)

            return request.make_response(simplejson.dumps({
                'appid': application.enterprise_id.corp_id,
                'dbname': cr.dbname,
                'agentid': application.application_id,
            }))
        else:
            return request.make_response({})
